#!/usr/bin/python3
# -*- coding: UTF-8 -*-

'''
awake558@qq.com

pip install --upgrade pip --user
pip install serial pyserial easygui psutil pillow matplotlib

'''

#from datetime import datetime
import datetime
import os
import shutil
import csv
import time
import sys
import re

import zipfile
import subprocess
import threading
import binascii
import optparse


from xml.etree.ElementTree import ElementTree
import struct

import json

from PIL import Image, ImageTk

import psutil

import matplotlib 
import numpy as np
import matplotlib as mpl
from matplotlib.widgets import Button,RadioButtons
from matplotlib.widgets import CheckButtons

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

import codecs

'''
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa8 in position

解决方法

import codecs

fr = open('test.txt')

改为如下即可解决问题：

fr= codecs.open('test.txt', 'r',encoding= u'utf-8',errors='ignore')

'''
def analyse(filename_main, filename_kernel, module, phone) :

    #print (module)
    ynumber_i = 0  # y number
    module_power_supply_update = False
    module_BatteryBroadcastReceiver = False
    module_DeviceStatusMonitor = False
    module_healthd = False

    if module :
        if re.search('all', module):
            module_power_supply_update = True
            module_BatteryBroadcastReceiver = True
            module_DeviceStatusMonitor = True
            module_healthd = True
            ynumber_i += 20
        if re.search('power_supply_update', module):
            module_power_supply_update = True
            ynumber_i += 3
        if re.search('BatteryBroadcastReceiver', module):
            module_BatteryBroadcastReceiver = True
            ynumber_i += 5
        if re.search('DeviceStatusMonitor', module):
            module_DeviceStatusMonitor = True
            ynumber_i += 5
        if re.search('healthd', module):
            module_healthd = True
            ynumber_i += 7
    if phone :
        if re.search('^u3x|u3sh$', phone) :
            if filename_main :
                module_power_supply_update = True
                module_DeviceStatusMonitor = True
                ynumber_i += 8
            if filename_kernel :
                module_healthd = True
                ynumber_i += 7
        if re.search('^u3$', phone) :
            if filename_main :
                module_power_supply_update = True
                module_BatteryBroadcastReceiver = True
                ynumber_i += 8
            if filename_kernel :
                module_healthd = True
                ynumber_i += 7

    print ("module_power_supply_update = " + str(module_power_supply_update), "\t\t\t\tline:%s" %sys._getframe().f_lineno)
    print ("module_BatteryBroadcastReceiver = " + str(module_BatteryBroadcastReceiver), "\t\t\tline:%s" %sys._getframe().f_lineno)
    print ("module_DeviceStatusMonitor = " + str(module_DeviceStatusMonitor), "\t\t\t\tline:%s" %sys._getframe().f_lineno)
    print ("module_healthd = " + str(module_healthd), "\t\t\t\t\t\tline:%s" %sys._getframe().f_lineno)

    #------------
    yi = 0 #y number

    part_plt = host_subplot(111, axes_class=AA.Axes)
    plt.subplots_adjust(right = 1 - ynumber_i * 0.03)

    if module_power_supply_update :
        part_ocv_uv = part_plt.twinx()
        part_ibatt = part_plt.twinx()
        part_seq_num = part_plt.twinx()
    if module_BatteryBroadcastReceiver :
        part_batteryLevel = part_plt.twinx()
        part_batteryVoltage = part_plt.twinx()
        part_batteryTemperature = part_plt.twinx()
        part_batteryStatus = part_plt.twinx()
        part_batteryHealth = part_plt.twinx()
    if module_DeviceStatusMonitor :
        part_DeviceStatusMonitor_batteryLevel = part_plt.twinx()
        part_DeviceStatusMonitor_batteryVoltage = part_plt.twinx()
        part_DeviceStatusMonitor_batteryTemperature = part_plt.twinx()
        part_DeviceStatusMonitor_batteryStatus = part_plt.twinx()
        part_DeviceStatusMonitor_batteryHealth = part_plt.twinx()
    if module_healthd :
        part_healthd_capacity = part_plt.twinx()
        part_healthd_voltage_now = part_plt.twinx()
        part_healthd_temp = part_plt.twinx()
        part_healthd_status = part_plt.twinx()
        part_healthd_current_now = part_plt.twinx()
        part_healthd_charge_full = part_plt.twinx()
        part_healthd_chg = part_plt.twinx()
 
    vm_bms_soc=""
    vm_bms_ocv_uv=""
    vm_bms_ibatt=""
    vm_bms_seq_num=""

    bbr_batteryLevel=""
    bbr_batteryVoltage=""
    bbr_batteryTemperature=""
    bbr_batteryStatus=""
    bbr_batteryHealth=""

    DeviceStatusMonitor_batteryLevel=""
    DeviceStatusMonitor_batteryVoltage=""
    DeviceStatusMonitor_batteryTemperature=""
    DeviceStatusMonitor_batteryStatus=""
    DeviceStatusMonitor_batteryHealth=""

    healthd_time=""
    healthd_capacity=""
    healthd_voltage_now=""
    healthd_temp=""
    healthd_health=""
    healthd_status=""
    healthd_current_now=""
    healthd_charge_full=""
    healthd_cycle_count=""
    healthd_chg=""

    list_vm_bms_time = []
    list_vm_bms_soc = []
    list_vm_bms_ocv_uv = []
    list_vm_bms_ibatt = []
    list_vm_bms_seq_num = []

    list_bbr_time = []
    list_bbr_batteryLevel = []
    list_bbr_batteryVoltage = []
    list_bbr_batteryTemperature = []
    list_bbr_batteryStatus = []
    list_bbr_batteryHealth = []

    list_DeviceStatusMonitor_time = []
    list_DeviceStatusMonitor_batteryLevel = []
    list_DeviceStatusMonitor_batteryVoltage = []
    list_DeviceStatusMonitor_batteryTemperature = []
    list_DeviceStatusMonitor_batteryStatus = []
    list_DeviceStatusMonitor_batteryHealth = []

    list_healthd_time = []
    list_healthd_capacity = []
    list_healthd_voltage_now = []
    list_healthd_temp = []
    list_healthd_health = []
    list_healthd_status = []
    list_healthd_current_now = []
    list_healthd_charge_full = []
    list_healthd_cycle_count = []
    list_healthd_chg = []

    if filename_main :
        filename = filename_main
    if filename_kernel :
        filename = filename_kernel

    # fin = open(filename, 'r', encoding="utf-8")
    fin = codecs.open(filename, 'r',encoding= u'utf-8',errors='ignore')
    fout = open('vm_bms.csv', 'w')

# 01-20 13:29:21.479   568   568 I VM_BMS  : power_supply_update: ocv_uv=4303637 ibatt=2352 soc=99 seq_num=295
# 01-20 13:30:09.857   568   568 I VM_BMS  : power_supply_update: ocv_uv=4303595 ibatt=7953 soc=99 seq_num=296
    for line in fin.readlines():
        line = line.strip()                             #remove tab and space
        if module_power_supply_update :
            if re.match('.+VM_BMS.+power_supply_update:', line):
                #print ("%s" % (line) )

                # 01-20 13:29:21.479
                var = re.search('[0-9]{2,2}-[0-9]{2,2}\ [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}\.[0-9]{3,3}' , line).group()
                #print (var)
                time_str = re.search('[0-9]{2,2}-[0-9]{2,2}\ [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}' , var).group()
                dot_sec_str = re.search('[0-9]{3,6}$' , var).group()

                match_time = '2021-' + time_str
                ans_time_stamp = time.mktime(time.strptime(match_time, "%Y-%m-%d %H:%M:%S"))
                ans_time_stamp_dot_sec = ans_time_stamp + float(dot_sec_str)/1000
                #print (ans_time_stamp_dot_sec)

                vm_bms_time = float(ans_time_stamp_dot_sec)
                #vm_bms_time = vm_bms_time1 * 1000000
                #print (vm_bms_time)

                list_vm_bms_time.append(vm_bms_time)

                # soc=99
                var = re.search('soc=[0-9]{1,3}' , line).group()
                #print (var)
                vm_bms_soc = int(re.search('[0-9]{1,3}' , var).group())
                #print (vm_bms_soc)

                list_vm_bms_soc.append(vm_bms_soc)

                # ocv_uv=4303637 
                var = re.search('ocv_uv=[0-9]{1,8}' , line).group()
                #print (var)
                vm_bms_ocv_uv = int(re.search('[0-9]{1,8}' , var).group())
                #print (vm_bms_ocv_uv)

                list_vm_bms_ocv_uv.append(vm_bms_ocv_uv)

                # ibatt=2352
                var = re.search('ibatt=[-]{0,1}[0-9]{1,7}' , line).group()
                #print (var)
                vm_bms_ibatt = int(re.search('[-]{0,1}[0-9]{1,7}' , var).group())
                #print (vm_bms_ibatt)

                list_vm_bms_ibatt.append(vm_bms_ibatt * -1)

                # seq_num=295
                var = re.search('seq_num=[0-9]{1,3}' , line).group()
                #print (var)
                vm_bms_seq_num = int(re.search('[0-9]{1,3}' , var).group())
                #print (vm_bms_seq_num)

                list_vm_bms_seq_num.append(vm_bms_seq_num)

        if module_BatteryBroadcastReceiver :
            if re.match('.+BatteryBroadcastReceiver', line):
                #print ("%s" % (line) )

                # 01-20 13:29:21.479
                var = re.search('[0-9]{2,2}-[0-9]{2,2}\ [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}\.[0-9]{3,3}' , line).group()
                #print (var)
                time_str = re.search('[0-9]{2,2}-[0-9]{2,2}\ [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}' , var).group()
                dot_sec_str = re.search('[0-9]{3,6}$' , var).group()
                
                match_time = '2021-' + time_str
                ans_time_stamp = time.mktime(time.strptime(match_time, "%Y-%m-%d %H:%M:%S"))
                ans_time_stamp_dot_sec = ans_time_stamp + float(dot_sec_str)/1000
                #print (ans_time_stamp_dot_sec)

                bbr_time = float(ans_time_stamp_dot_sec)
                #bbr_time = bbr_time1 * 1000000
                #print (bbr_time)

                list_bbr_time.append(bbr_time)

                # batteryLevel=43
                var = re.search('batteryLevel=[0-9]{1,3}' , line).group()
                #print (var)
                bbr_batteryLevel = int(re.search('[0-9]{1,3}' , var).group())
                #print (bbr_batteryLevel)

                list_bbr_batteryLevel.append(bbr_batteryLevel)

                # batteryVoltage=4128
                var = re.search('batteryVoltage=[0-9]{1,4}' , line).group()
                #print (var)
                bbr_batteryVoltage = int(re.search('[0-9]{1,4}' , var).group())
                #print (bbr_batteryVoltage)

                list_bbr_batteryVoltage.append(bbr_batteryVoltage)

                # batteryTemperature=443
                var = re.search('batteryTemperature=[0-9]{1,3}' , line).group()
                #print (var)
                bbr_batteryTemperature = int(re.search('[0-9]{1,3}' , var).group())
                #print (bbr_batteryTemperature)

                list_bbr_batteryTemperature.append(bbr_batteryTemperature)

                # batteryStatus=2
                var = re.search('batteryStatus=[0-9]{1,1}' , line).group()
                #print (var)
                bbr_batteryStatus = int(re.search('[0-9]{1,1}' , var).group())
                #print (bbr_batteryStatus)

                list_bbr_batteryStatus.append(bbr_batteryStatus)

                # batteryHealth=2
                var = re.search('batteryHealth=[0-9]{1,1}' , line).group()
                #print (var)
                bbr_batteryHealth = int(re.search('[0-9]{1,1}' , var).group())
                #print (bbr_batteryHealth)

                list_bbr_batteryHealth.append(bbr_batteryHealth)

        # 02-24 10:20:59.407  1507  1507 D [main][DeviceStatusMonitor#onReceive]: battery: get battery change 4 3671 332 3 1
        # 04-14 10:36:37.541  1389  1389 D [main][DeviceStatusMonitor#onReceive]: battery: get battery change 100 4355 309 2 2
        # 04-14 14:55:32.082  1389  1389 D [main][DeviceStatusMonitor#onReceive]: shutdownReceiver action = com.glocalme.glocalmehome.shutdown1
        if module_DeviceStatusMonitor :
            if re.match('.+DeviceStatusMonitor.+battery', line):
                #print ("%s" % (line) + "\t\t\t\tline:%s" %sys._getframe().f_lineno)

                # 01-20 13:29:21.479
                var = re.search('[0-9]{2,2}-[0-9]{2,2}\ [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}\.[0-9]{3,3}' , line).group()
                #print (var)
                time_str = re.search('[0-9]{2,2}-[0-9]{2,2}\ [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}' , var).group()
                dot_sec_str = re.search('[0-9]{3,6}$' , var).group()
                
                match_time = '2021-' + time_str
                ans_time_stamp = time.mktime(time.strptime(match_time, "%Y-%m-%d %H:%M:%S"))
                ans_time_stamp_dot_sec = ans_time_stamp + float(dot_sec_str)/1000
                #print (ans_time_stamp_dot_sec)

                DeviceStatusMonitor_time = float(ans_time_stamp_dot_sec)
                #DeviceStatusMonitor_time = bbr_time1 * 1000000
                #print (str(DeviceStatusMonitor_time) + "\t\t\t\tline:%s" %sys._getframe().f_lineno)

                list_DeviceStatusMonitor_time.append(DeviceStatusMonitor_time)

                # batteryLevel=43            4 3671 332 3 1
                # battery: get battery change 100 4355 309 2 2
                var = re.search('([0-9]{1,4})\ ([0-9]{4,4})\ ([0-9]{3,3})\ ([0-9]{1,1})\ ([0-9]{1,1})' , line).group(1)
                #print (var + "\t\t\t\tline:%s" %sys._getframe().f_lineno)
                DeviceStatusMonitor_batteryLevel = int(re.search('[0-9]{1,3}' , var).group())
                #print (DeviceStatusMonitor_batteryLevel)

                list_DeviceStatusMonitor_batteryLevel.append(DeviceStatusMonitor_batteryLevel)

                # batteryVoltage=4128            4 3671 332 3 1
                var = re.search('([0-9]{1,3})\ ([0-9]{4,4})\ ([0-9]{3,3})\ ([0-9]{1,1})\ ([0-9]{1,1})' , line).group(2)
                #print (var)
                DeviceStatusMonitor_batteryVoltage = int(re.search('[0-9]{1,4}' , var).group())
                #print (DeviceStatusMonitor_batteryVoltage)

                list_DeviceStatusMonitor_batteryVoltage.append(DeviceStatusMonitor_batteryVoltage)

                # batteryTemperature=443            4 3671 332 3 1
                var = re.search('([0-9]{1,3})\ ([0-9]{4,4})\ ([0-9]{3,3})\ ([0-9]{1,1})\ ([0-9]{1,1})' , line).group(3)
                #print (var)
                DeviceStatusMonitor_batteryTemperature = int(re.search('[0-9]{1,3}' , var).group())
                #print (DeviceStatusMonitor_batteryTemperature)            4 3671 332 3 1

                list_DeviceStatusMonitor_batteryTemperature.append(DeviceStatusMonitor_batteryTemperature)

                # batteryStatus=2            4 3671 332 3 1
                var = re.search('([0-9]{1,3})\ ([0-9]{4,4})\ ([0-9]{3,3})\ ([0-9]{1,1})\ ([0-9]{1,1})' , line).group(4)
                #print (var)
                DeviceStatusMonitor_batteryStatus = int(re.search('[0-9]{1,1}' , var).group())
                #print (DeviceStatusMonitor_batteryStatus)

                list_DeviceStatusMonitor_batteryStatus.append(DeviceStatusMonitor_batteryStatus)

                # batteryHealth=2            4 3671 332 3 1
                var = re.search('([0-9]{1,3})\ ([0-9]{4,4})\ ([0-9]{3,3})\ ([0-9]{1,1})\ ([0-9]{1,1})' , line).group(5)
                #print (var)
                DeviceStatusMonitor_batteryHealth = int(re.search('[0-9]{1,1}' , var).group())
                #print (DeviceStatusMonitor_batteryHealth)

                list_DeviceStatusMonitor_batteryHealth.append(DeviceStatusMonitor_batteryHealth)

        if module_healthd :
            #  xiao mi 10 main log
            #  03-01 09:25:22.354     0     0 W healthd : battery l=3 v=3630 t=22.0 h=2 st=2 c=-94 fc=4735000 cc=17 tl=0 ct=USB_DCP chg=a
            if re.match('.+healthd\ *:\ battery', line):
                #print ("%s" % (line) , "\t\t\t\tline:%s" %sys._getframe().f_lineno)

                # 01-20 13:29:21.479
                var = re.search('[0-9]{2,2}-[0-9]{2,2}\ [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}\.[0-9]{1,3}' , line).group()
                #print (var , "\t\t\t\tline:%s" %sys._getframe().f_lineno)
                time_str = re.search('[0-9]{2,2}-[0-9]{2,2}\ [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}' , var).group()
                dot_sec_str = re.search('[0-9]{1,6}$' , var).group()
                
                match_time = '2021-' + time_str
                ans_time_stamp = time.mktime(time.strptime(match_time, "%Y-%m-%d %H:%M:%S"))
                ans_time_stamp_dot_sec = ans_time_stamp + float(dot_sec_str)/1000
                #print (ans_time_stamp_dot_sec , "\t\t\t\tline:%s" %sys._getframe().f_lineno)

                healthd_time = float(ans_time_stamp_dot_sec)
                #healthd_time = bbr_time1 * 1000000
                #print (healthd_time , "\t\t\t\tline:%s" %sys._getframe().f_lineno)

                list_healthd_time.append(healthd_time)

                # l=37
                var = re.search('l=[0-9]{1,3}' , line).group()
                #print (var , "\t\t\t\tline:%s" %sys._getframe().f_lineno)
                healthd_capacity = int(re.search('[0-9]{1,3}' , var).group())
                #print (healthd_capacity , "\t\t\t\tline:%s" %sys._getframe().f_lineno)

                list_healthd_capacity.append(healthd_capacity)

                # v=3769
                var = re.search('v=[0-9]{1,4}' , line).group()
                #print (var , "\t\t\t\tline:%s" %sys._getframe().f_lineno)
                healthd_voltage_now = int(re.search('[0-9]{1,4}' , var).group())
                #print (healthd_voltage_now , "\t\t\t\tline:%s" %sys._getframe().f_lineno)

                list_healthd_voltage_now.append(healthd_voltage_now)

                # t=24.0
                var = re.search('t=[0-9]{1,3}.[0-9]{1,3}' , line).group()
                #print (var , "\t\t\t\tline:%s" %sys._getframe().f_lineno)
                healthd_temp = float(re.search('[0-9]{1,3}.[0-9]{1,3}' , var).group())
                #print (healthd_temp , "\t\t\t\tline:%s" %sys._getframe().f_lineno)

                list_healthd_temp.append(healthd_temp)

                # h=1
                var = re.search('h=[0-9]{1,1}' , line).group()
                #print (var , "\t\t\t\tline:%s" %sys._getframe().f_lineno)
                healthd_health = int(re.search('[0-9]{1,1}' , var).group())
                #print (healthd_health , "\t\t\t\tline:%s" %sys._getframe().f_lineno)

                list_healthd_health.append(healthd_health)

                # st=3
                var = re.search('st=[0-9]{1,1}' , line).group()
                #print (var , "\t\t\t\tline:%s" %sys._getframe().f_lineno)
                healthd_status = int(re.search('[0-9]{1,1}' , var).group())
                #print (healthd_status , "\t\t\t\tline:%s" %sys._getframe().f_lineno)

                list_healthd_status.append(healthd_status)

                # c=73
                var = re.search('c=[0-9]{1,6}' , line).group()
                #print (var , "\t\t\t\tline:%s" %sys._getframe().f_lineno)
                healthd_current_now = int(re.search('[0-9]{1,5}' , var).group())
                #print (healthd_current_now , "\t\t\t\tline:%s" %sys._getframe().f_lineno)

                list_healthd_current_now.append(healthd_current_now)

                # fc=0
                var = re.search('fc=[0-9]{1,1}' , line).group()
                #print (var , "\t\t\t\tline:%s" %sys._getframe().f_lineno)
                healthd_charge_full = int(re.search('[0-9]{1,1}' , var).group())
                #print (healthd_charge_full , "\t\t\t\tline:%s" %sys._getframe().f_lineno)

                list_healthd_charge_full.append(healthd_charge_full)

                # cc=4
                var = re.search('cc=[0-9]{1,1}' , line).group()
                #print (var , "\t\t\t\tline:%s" %sys._getframe().f_lineno)
                healthd_cycle_count = int(re.search('[0-9]{1,1}' , var).group())
                #print (healthd_cycle_count , "\t\t\t\tline:%s" %sys._getframe().f_lineno)

                list_healthd_cycle_count.append(healthd_cycle_count)

                # chg=
                var = re.search('chg=[a-z]{0,3}' , line).group()
                #print (var , "\t\t\t\tline:%s" %sys._getframe().f_lineno)
                healthd_chg = re.search('[a-z]{0,3}$' , var).group()
                #print (healthd_chg , "\t\t\t\tline:%s" %sys._getframe().f_lineno)
                # null a u w au
                #   0  1 2 3 4
                if healthd_chg == 'a' :
                    list_healthd_chg.append(1)
                elif healthd_chg == 'u' :
                    list_healthd_chg.append(2)
                elif healthd_chg == 'w' :
                    list_healthd_chg.append(3)
                elif healthd_chg == 'au' :
                    list_healthd_chg.append(4)
                else :
                    list_healthd_chg.append(0)
        
    fout.close()
    fin.close()


    #print ("list_vm_bms_time = " + str(len(list_vm_bms_time)))
    #print ("list_vm_bms_soc = " + str(len(list_vm_bms_soc)))
    #print ("list_vm_bms_ocv_uv = " + str(len(list_vm_bms_ocv_uv)))
    #print ("list_vm_bms_ibatt = " + str(len(list_vm_bms_ibatt)))
    #print ("list_vm_bms_seq_num = " + str(len(list_vm_bms_seq_num)))
    #print ("list_healthd_status = " + str(len(list_healthd_status)))
    #print ("list_healthd_charge_full = " + str(len(list_healthd_charge_full)))
    #print ("list_healthd_cycle_count = " + str(len(list_healthd_cycle_count)))
    #print ("list_healthd_chg = " + str(len(list_healthd_chg)))


# marker https://matplotlib.org/3.2.1/api/markers_api.html
    if module_power_supply_update :
        p1, = part_plt.plot(list_vm_bms_time, list_vm_bms_soc, label="soc" ) # , marker='s')
        p2, = part_ocv_uv.plot(list_vm_bms_time, list_vm_bms_ocv_uv, label="ocv_uv" ) # , marker='s')
        p3, = part_ibatt.plot(list_vm_bms_time, list_vm_bms_ibatt, label="ibatt" ) # , marker='s')
        p4, = part_seq_num.plot(list_vm_bms_time, list_vm_bms_seq_num, label="seq_num" ) # , marker='s')

    if module_BatteryBroadcastReceiver :
        p5, = part_batteryLevel.plot(list_bbr_time, list_bbr_batteryLevel, label="batteryLevel" ) # , marker='s')
        p6, = part_batteryVoltage.plot(list_bbr_time, list_bbr_batteryVoltage, label="batteryVoltage" ) # , marker='s')
        p7, = part_batteryTemperature.plot(list_bbr_time, list_bbr_batteryTemperature, label="batteryTemperature" ) # , marker='s')
        p8, = part_batteryStatus.plot(list_bbr_time, list_bbr_batteryStatus, label="batteryStatus" ) # , marker='s')
        p9, = part_batteryHealth.plot(list_bbr_time, list_bbr_batteryHealth, label="batteryHealth" ) # , marker='s')

    if module_DeviceStatusMonitor :
        p10, = part_DeviceStatusMonitor_batteryLevel.plot(list_DeviceStatusMonitor_time, list_DeviceStatusMonitor_batteryLevel, label="bLevel" ) # , marker='s')
        p11, = part_DeviceStatusMonitor_batteryVoltage.plot(list_DeviceStatusMonitor_time, list_DeviceStatusMonitor_batteryVoltage, label="bVoltage" ) # , marker='s')
        p12, = part_DeviceStatusMonitor_batteryTemperature.plot(list_DeviceStatusMonitor_time, list_DeviceStatusMonitor_batteryTemperature, label="bTemperature" ) # , marker='s')
        p13, = part_DeviceStatusMonitor_batteryStatus.plot(list_DeviceStatusMonitor_time, list_DeviceStatusMonitor_batteryStatus, label="bStatus" ) # , marker='s')
        p14, = part_DeviceStatusMonitor_batteryHealth.plot(list_DeviceStatusMonitor_time, list_DeviceStatusMonitor_batteryHealth, label="bHealth" ) # , marker='s')

    if module_healthd :
        p21, = part_healthd_capacity.plot(list_healthd_time, list_healthd_capacity, label="capacity" ) # , marker='s')
        p22, = part_healthd_voltage_now.plot(list_healthd_time, list_healthd_voltage_now, label="voltage" ) # , marker='s')
        p23, = part_healthd_temp.plot(list_healthd_time, list_healthd_temp, label="temp" ) # , marker='s')
        p24, = part_healthd_status.plot(list_healthd_time, list_healthd_status, label="status" ) # , marker='s')
        p25, = part_healthd_current_now.plot(list_healthd_time, list_healthd_current_now, label="current" ) # , marker='s')
        p26, = part_healthd_charge_full.plot(list_healthd_time, list_healthd_charge_full, label="charge_full" ) # , marker='s')
        p27, = part_healthd_chg.plot(list_healthd_time, list_healthd_chg, label="chg" ) # , marker='s')

    
    
    part_plt.legend()  # show legend (tuli), must put it behind p1, p2, 

    if module_power_supply_update :

        offset = yi
        yi += 40
        new_fixed_axis = part_ocv_uv.get_grid_helper().new_fixed_axis
        part_ocv_uv.axis["right"] = new_fixed_axis(loc="right", axes=part_ocv_uv, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_ibatt.get_grid_helper().new_fixed_axis
        part_ibatt.axis["right"] = new_fixed_axis(loc="right", axes=part_ibatt, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_seq_num.get_grid_helper().new_fixed_axis
        part_seq_num.axis["right"] = new_fixed_axis(loc="right", axes=part_seq_num, offset=(offset, 10))


        part_ocv_uv.axis["right"].toggle(all=True)
        part_ibatt.axis["right"].toggle(all=True)
        part_seq_num.axis["right"].toggle(all=True)

        part_plt.set_ylim(0, 105)

        #part_ibatt.set_ylim(-10000, 10000)
        #part_seq_num.set_ylim(-1, 6)
        #part_plt.set_xlim(0, 2)  # limit x
        #part_plt.set_ylim(0, 2)  # limit y

        part_plt.set_xlabel("Times")
        part_plt.set_ylabel("soc")
        #part_ibatt.invert_yaxis() # invert y

        part_ocv_uv.set_ylabel("ocv_uv")
        part_ibatt.set_ylabel("ibatt")
        part_seq_num.set_ylabel("seq_num")
        part_ocv_uv.yaxis.set_label_coords(-0.5,0.5)



        part_plt.axis["left"].label.set_color(p1.get_color())
        part_ocv_uv.axis["right"].label.set_color(p2.get_color())
        part_ibatt.axis["right"].label.set_color(p3.get_color())
        part_seq_num.axis["right"].label.set_color(p4.get_color())

    if module_BatteryBroadcastReceiver :
        offset = yi
        yi += 40
        new_fixed_axis = part_batteryLevel.get_grid_helper().new_fixed_axis
        part_batteryLevel.axis["right"] = new_fixed_axis(loc="right", axes=part_batteryLevel, offset=(offset, 0))

        offset = yi
        yi += 40
        new_fixed_axis = part_batteryVoltage.get_grid_helper().new_fixed_axis
        part_batteryVoltage.axis["right"] = new_fixed_axis(loc="right", axes=part_batteryVoltage, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_batteryTemperature.get_grid_helper().new_fixed_axis
        part_batteryTemperature.axis["right"] = new_fixed_axis(loc="right", axes=part_batteryTemperature, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_batteryStatus.get_grid_helper().new_fixed_axis
        part_batteryStatus.axis["right"] = new_fixed_axis(loc="right", axes=part_batteryStatus, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_batteryHealth.get_grid_helper().new_fixed_axis
        part_batteryHealth.axis["right"] = new_fixed_axis(loc="right", axes=part_batteryHealth, offset=(offset, 10))

        part_batteryLevel.axis["right"].toggle(all=True)
        part_batteryVoltage.axis["right"].toggle(all=True)
        part_batteryTemperature.axis["right"].toggle(all=True)
        part_batteryStatus.axis["right"].toggle(all=True)
        part_batteryHealth.axis["right"].toggle(all=True)

        part_batteryLevel.set_ylim(0, 105)
        part_batteryHealth.set_ylim(0, 10)

        # set y label
        part_batteryLevel.set_ylabel("batteryLevel")
        part_batteryVoltage.set_ylabel("batteryVoltage")
        part_batteryTemperature.set_ylabel("batteryTemperature")
        part_batteryStatus.set_ylabel("batteryStatus 1:Unknown; 2:Charging; 3:Discharging; 4:Not charging; 5:full")
        part_batteryHealth.set_ylabel("batteryHealth")

        # set y label color
        part_batteryLevel.axis["right"].label.set_color(p5.get_color())
        part_batteryVoltage.axis["right"].label.set_color(p6.get_color())
        part_batteryTemperature.axis["right"].label.set_color(p7.get_color())
        part_batteryStatus.axis["right"].label.set_color(p8.get_color())
        part_batteryHealth.axis["right"].label.set_color(p9.get_color())

    if module_DeviceStatusMonitor :
        offset = yi
        yi += 40
        new_fixed_axis = part_DeviceStatusMonitor_batteryLevel.get_grid_helper().new_fixed_axis
        part_DeviceStatusMonitor_batteryLevel.axis["right"] = new_fixed_axis(loc="right", axes=part_DeviceStatusMonitor_batteryLevel, offset=(offset, 0))

        offset = yi
        yi += 40
        new_fixed_axis = part_DeviceStatusMonitor_batteryVoltage.get_grid_helper().new_fixed_axis
        part_DeviceStatusMonitor_batteryVoltage.axis["right"] = new_fixed_axis(loc="right", axes=part_DeviceStatusMonitor_batteryVoltage, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_DeviceStatusMonitor_batteryTemperature.get_grid_helper().new_fixed_axis
        part_DeviceStatusMonitor_batteryTemperature.axis["right"] = new_fixed_axis(loc="right", axes=part_DeviceStatusMonitor_batteryTemperature, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_DeviceStatusMonitor_batteryStatus.get_grid_helper().new_fixed_axis
        part_DeviceStatusMonitor_batteryStatus.axis["right"] = new_fixed_axis(loc="right", axes=part_DeviceStatusMonitor_batteryStatus, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_DeviceStatusMonitor_batteryHealth.get_grid_helper().new_fixed_axis
        part_DeviceStatusMonitor_batteryHealth.axis["right"] = new_fixed_axis(loc="right", axes=part_DeviceStatusMonitor_batteryHealth, offset=(offset, 10))

        part_DeviceStatusMonitor_batteryLevel.axis["right"].toggle(all=True)
        part_DeviceStatusMonitor_batteryVoltage.axis["right"].toggle(all=True)
        part_DeviceStatusMonitor_batteryTemperature.axis["right"].toggle(all=True)
        part_DeviceStatusMonitor_batteryStatus.axis["right"].toggle(all=True)
        part_DeviceStatusMonitor_batteryHealth.axis["right"].toggle(all=True)

        part_DeviceStatusMonitor_batteryLevel.set_ylim(0, 105)
        part_DeviceStatusMonitor_batteryHealth.set_ylim(0, 10)

        # set y label
        part_DeviceStatusMonitor_batteryLevel.set_ylabel("bLevel")
        part_DeviceStatusMonitor_batteryVoltage.set_ylabel("bVoltage")
        part_DeviceStatusMonitor_batteryTemperature.set_ylabel("bTemperature")
        part_DeviceStatusMonitor_batteryStatus.set_ylabel("bStatus 1:Unknown; 2:Charging; 3:Discharging; 4:Not charging; 5:full")
        part_DeviceStatusMonitor_batteryHealth.set_ylabel("bHealth")

        # set y label color
        part_DeviceStatusMonitor_batteryLevel.axis["right"].label.set_color(p10.get_color())
        part_DeviceStatusMonitor_batteryVoltage.axis["right"].label.set_color(p11.get_color())
        part_DeviceStatusMonitor_batteryTemperature.axis["right"].label.set_color(p12.get_color())
        part_DeviceStatusMonitor_batteryStatus.axis["right"].label.set_color(p13.get_color())
        part_DeviceStatusMonitor_batteryHealth.axis["right"].label.set_color(p14.get_color())

    if module_healthd :
        offset = yi
        yi += 40
        new_fixed_axis = part_healthd_capacity.get_grid_helper().new_fixed_axis
        part_healthd_capacity.axis["right"] = new_fixed_axis(loc="right", axes=part_healthd_capacity, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_healthd_voltage_now.get_grid_helper().new_fixed_axis
        part_healthd_voltage_now.axis["right"] = new_fixed_axis(loc="right", axes=part_healthd_voltage_now, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_healthd_temp.get_grid_helper().new_fixed_axis
        part_healthd_temp.axis["right"] = new_fixed_axis(loc="right", axes=part_healthd_temp, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_healthd_status.get_grid_helper().new_fixed_axis
        part_healthd_status.axis["right"] = new_fixed_axis(loc="right", axes=part_healthd_status, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_healthd_current_now.get_grid_helper().new_fixed_axis
        part_healthd_current_now.axis["right"] = new_fixed_axis(loc="right", axes=part_healthd_current_now, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_healthd_charge_full.get_grid_helper().new_fixed_axis
        part_healthd_charge_full.axis["right"] = new_fixed_axis(loc="right", axes=part_healthd_charge_full, offset=(offset, 10))

        offset = yi
        yi += 40
        new_fixed_axis = part_healthd_chg.get_grid_helper().new_fixed_axis
        part_healthd_chg.axis["right"] = new_fixed_axis(loc="right", axes=part_healthd_chg, offset=(offset, 10))

        part_healthd_capacity.axis["right"].toggle(all=True)
        part_healthd_voltage_now.axis["right"].toggle(all=True)
        part_healthd_temp.axis["right"].toggle(all=True)
        part_healthd_status.axis["right"].toggle(all=True)
        part_healthd_current_now.axis["right"].toggle(all=True)
        part_healthd_charge_full.axis["right"].toggle(all=True)
        part_healthd_chg.axis["right"].toggle(all=True)
    
        part_healthd_capacity.set_ylim(0, 105)
        part_healthd_status.set_ylim(-0.6, 6)
        part_healthd_charge_full.set_ylim(-2, 7)
        part_healthd_chg.set_ylim(-1, 5)  # limit y
        #part_healthd_capacity.set_xlim(0, 2)  # limit x
        #part_healthd_capacity.set_ylim(0, 2)  # limit y

        part_healthd_capacity.set_ylabel("capacity")
        #part_healthd_capacity.invert_yaxis() # invert y
        part_healthd_voltage_now.set_ylabel("voltage")
        part_healthd_temp.set_ylabel("temp")
        part_healthd_status.set_ylabel("status 1:Unknown; 2:Charging; 3:Discharging; 4:Not charging; 5:full")
        part_healthd_current_now.set_ylabel("current")
        part_healthd_charge_full.set_ylabel("charge_full")
        part_healthd_chg.set_ylabel("chg 0:null 1:a 2:u 3:w 4:au")
        
        part_healthd_capacity.axis["left"].label.set_color(p21.get_color())
        part_healthd_voltage_now.axis["right"].label.set_color(p22.get_color())
        part_healthd_temp.axis["right"].label.set_color(p23.get_color())
        part_healthd_status.axis["right"].label.set_color(p24.get_color())
        part_healthd_current_now.axis["right"].label.set_color(p25.get_color())
        part_healthd_charge_full.axis["right"].label.set_color(p26.get_color())
        part_healthd_chg.axis["right"].label.set_color(p27.get_color())
        
        
    plt.grid()
    plt.draw()
    #plt.show()

    if module_power_supply_update :
        lines = [p1, p2, p3, p4]
        rax = plt.axes([0.75, 0.9, 0.1, 0.1])
        labels = [str(line.get_label()) for line in lines]
        visibility = [line.get_visible() for line in lines]
        check = CheckButtons(rax, labels, visibility)

    if module_BatteryBroadcastReceiver :
        lines2 = [p5, p6, p7, p8, p9]
        rax2 = plt.axes([0.85, 0.9, 0.1, 0.1])
        labels2 = [str(line.get_label()) for line in lines2]
        visibility2 = [line.get_visible() for line in lines2]
        check2 = CheckButtons(rax2, labels2, visibility2)

    if module_DeviceStatusMonitor :
        lines3 = [p10, p11, p12, p13, p14]
        rax3 = plt.axes([0.65, 0.9, 0.1, 0.1])
        labels3 = [str(line.get_label()) for line in lines3]
        visibility3 = [line.get_visible() for line in lines3]
        check3 = CheckButtons(rax3, labels3,  visibility3)

    if module_healthd :
        lines4 = [p21, p22, p23, p24, p25, p26, p27]
        rax4 = plt.axes([0.55, 0.9, 0.1, 0.1])
        labels4 = [str(line.get_label()) for line in lines4]
        visibility4 = [line.get_visible() for line in lines4]
        check4 = CheckButtons(rax4, labels4, visibility4)
    
    
    
    def func(label):
        if module_power_supply_update :
            index = labels.index(label)
            lines[index].set_visible(not lines[index].get_visible())
            plt.draw()

    def func2(label2):
        if module_BatteryBroadcastReceiver :
            index = labels2.index(label2)
            lines2[index].set_visible(not lines2[index].get_visible())
            plt.draw()

    def func3(label3):
        if module_DeviceStatusMonitor :
            index = labels3.index(label3)
            lines3[index].set_visible(not lines3[index].get_visible())
            plt.draw()

    def func4(label4):
        if module_healthd :
            index = labels4.index(label4)
            lines4[index].set_visible(not lines4[index].get_visible())
            plt.draw()
    
    

    if module_power_supply_update :
        check.on_clicked(func)
    if module_BatteryBroadcastReceiver :
        check2.on_clicked(func2)
    if module_DeviceStatusMonitor :
        check3.on_clicked(func3)
    if module_healthd :
        check4.on_clicked(func4)


    # 画布最大化
    # mng = plt.get_current_fig_manager()
    # mng.resize(*mng.window.maxsize())

    plt.savefig('vmbms.jpg')
    plt.show()



'''
u3sh 
02-23 02:30:05.826  1440  1440 D [main][DeviceStatusMonitor#onReceive]: battery: get battery change 92 4124 301 2 2
[ 2689.848137] healthd: battery l=89 v=4198 t=29.9 h=2 st=2 c=111 fc=0 cc=58 chg=u
'''

'''
Time 模块

1	time.altzone            返回格林威治西部的夏令时地区的偏移秒数。如果该地区在格林威治东部会返回负值（如西欧，包括英国）。对夏令时启用地区才能使用。
2	time.asctime([tupletime])    接受时间元组并返回一个可读的形式为"Tue Dec 11 18:07:14 2008"（2008年12月11日 周二18时07分14秒）的24个字符的字符串。
3	time.clock()            用以浮点数计算的秒数返回当前的CPU时间。用来衡量不同程序的耗时，比time.time()更有用。
4	time.ctime([secs])      作用相当于asctime(localtime(secs))，未给参数相当于asctime()
5	time.gmtime([secs])     接收时间戳（1970纪元后经过的浮点秒数）并返回格林威治天文时间下的时间元组t。注：t.tm_isdst始终为0
6	time.localtime([secs])  接收时间戳（1970纪元后经过的浮点秒数）并返回当地时间下的时间元组t（t.tm_isdst可取0或1，取决于当地当时是不是夏令时）。
7	time.mktime(tupletime)  接受时间元组并返回时间戳（1970纪元后经过的浮点秒数）。
8	time.sleep(secs)        推迟调用线程的运行，secs指秒数。
9	time.strftime(fmt[,tupletime])  接收以时间元组，并返回以可读字符串表示的当地时间，格式由fmt决定。
10	time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')   根据fmt的格式把一个时间字符串解析为时间元组。
11	time.time()             返回当前时间的时间戳（1970纪元后经过的浮点秒数）。
12	time.tzset()            根据环境变量TZ重新初始化时间相关设置。

Time模块包含了以下2个非常重要的属性：
1	time.timezone           属性 time.timezone 是当地时区（未启动夏令时）距离格林威治的偏移秒数（>0，美洲<=0大部分欧洲，亚洲，非洲）。
2	time.tzname             属性time.tzname包含一对根据情况的不同而不同的字符串，分别是带夏令时的本地时区名称，和不带的。







Python time strptime()方法

描述
Python time strptime() 函数根据指定的格式把一个时间字符串解析为时间元组。

语法
strptime()方法语法：
time.strptime(string[, format])
    string -- 时间字符串。
    format -- 格式化字符串。

返回值
返回struct_time对象。

说明
python中时间日期格式化符号：

    %y 两位数的年份表示（00-99）
    %Y 四位数的年份表示（000-9999）
    %m 月份（01-12）
    %d 月内中的一天（0-31）
    %H 24小时制小时数（0-23）
    %I 12小时制小时数（01-12）
    %M 分钟数（00-59）
    %S 秒（00-59）
    %a 本地简化星期名称
    %A 本地完整星期名称
    %b 本地简化的月份名称
    %B 本地完整的月份名称
    %c 本地相应的日期表示和时间表示
    %j 年内的一天（001-366）
    %p 本地A.M.或P.M.的等价符
    %U 一年中的星期数（00-53）星期天为星期的开始
    %w 星期（0-6），星期天为 0，星期一为 1，以此类推。
    %W 一年中的星期数（00-53）星期一为星期的开始
    %x 本地相应的日期表示
    %X 本地相应的时间表示
    %Z 当前时区的名称
    %% %号本身

Python time mktime()方法

描述
Python time mktime() 函数执行与 gmtime(), localtime()相反的操作，它接收struct_time对象作为参数，返回用秒数来表示时间的浮点数。
如果输入的值不是一个合法的时间，将触发 OverflowError 或 ValueError。语法

mktime()方法语法：
time.mktime(t)

参数
    t -- 结构化的时间或者完整的9位元组元素。

返回值
返回用秒数来表示时间的浮点数。

'''
def merge_main_kernel(filename_main, filename_kernel, module, phone) :

    list_main = []
    dict_main_temp = {}
    list_kernel = []
    dict_kernel_temp = {}

    list_result = []


    module_power_supply_update = False
    module_BatteryBroadcastReceiver = False
    module_DeviceStatusMonitor = False
    module_healthd = False

    if phone :
        if re.search('^u3x|u3sh$', phone) :
            if filename_main :
                module_DeviceStatusMonitor = True
            if filename_kernel :
                module_healthd = True
        if re.search('^u3$', phone) :
            if filename_main :
                module_BatteryBroadcastReceiver = True
            if filename_kernel :
                module_healthd = True

    print ("module_power_supply_update = " + str(module_power_supply_update))
    print ("module_BatteryBroadcastReceiver = " + str(module_BatteryBroadcastReceiver))
    print ("module_DeviceStatusMonitor = " + str(module_DeviceStatusMonitor))
    print ("module_healthd = " + str(module_healthd))

    #fin_main = open(filename_main, 'r', encoding="utf-8")
    fin_main = codecs.open(filename_main, 'r',encoding= u'utf-8',errors='ignore')
    for line in fin_main.readlines():
        #print ("%s" % (line) + "\t\t\t\tline:%s" %sys._getframe().f_lineno)

        if module_BatteryBroadcastReceiver :
            if re.match('.+BatteryBroadcastReceiver', line):
                #print ("%s" % (line) )

                # 01-20 13:29:21.479
                var = re.search('[0-9]{2,2}-[0-9]{2,2}\ [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}\.[0-9]{3,3}' , line).group()
                #print (var)
                time_str = re.search('[0-9]{2,2}-[0-9]{2,2}\ [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}' , var).group()
                dot_sec_str = re.search('[0-9]{3,6}$' , var).group()
                
                match_time = '2021-' + time_str
                ans_time_stamp = time.mktime(time.strptime(match_time, "%Y-%m-%d %H:%M:%S"))
                ans_time_stamp_dot_sec = ans_time_stamp + float(dot_sec_str)/1000
                #print (ans_time_stamp_dot_sec)
                dict_main_temp.update({'ans_time_stamp_dot_sec':ans_time_stamp_dot_sec})

                # batteryLevel=43
                var = re.search('batteryLevel=[0-9]{1,3}' , line).group()
                #print (var)
                bbr_batteryLevel = int(re.search('[0-9]{1,3}' , var).group())
                #print (bbr_batteryLevel)
                dict_main_temp.update({'bbr_batteryLevel':bbr_batteryLevel})


                # batteryVoltage=4128
                var = re.search('batteryVoltage=[0-9]{1,4}' , line).group()
                #print (var)
                bbr_batteryVoltage = int(re.search('[0-9]{1,4}' , var).group())
                #print (bbr_batteryVoltage)
                dict_main_temp.update({'bbr_batteryVoltage':bbr_batteryVoltage})

                # batteryTemperature=443
                var = re.search('batteryTemperature=[0-9]{1,3}' , line).group()
                #print (var)
                bbr_batteryTemperature = int(re.search('[0-9]{1,3}' , var).group())
                #print (bbr_batteryTemperature)
                dict_main_temp.update({'bbr_batteryTemperature':bbr_batteryTemperature})

                # batteryStatus=2
                var = re.search('batteryStatus=[0-9]{1,1}' , line).group()
                #print (var)
                bbr_batteryStatus = int(re.search('[0-9]{1,1}' , var).group())
                #print (bbr_batteryStatus)
                dict_main_temp.update({'bbr_batteryStatus':bbr_batteryStatus})

                # batteryHealth=2
                var = re.search('batteryHealth=[0-9]{1,1}' , line).group()
                #print (var)
                bbr_batteryHealth = int(re.search('[0-9]{1,1}' , var).group())
                #print (bbr_batteryHealth)
                dict_main_temp.update({'bbr_batteryHealth':bbr_batteryHealth})

                #print (dict_main_temp)
                
                list_main.append(dict_main_temp)
                dict_main_temp = {}

                #print (list_main)

        if module_DeviceStatusMonitor :
            if re.match('.+DeviceStatusMonitor.+battery', line):
                # 01-20 13:29:21.479
                var = re.search('[0-9]{2,2}-[0-9]{2,2}\ [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}\.[0-9]{3,3}' , line).group()
                #print (var + "\t\t\t\tline:%s" %sys._getframe().f_lineno)
                time_str = re.search('[0-9]{2,2}-[0-9]{2,2}\ [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}' , var).group()
                dot_sec_str = re.search('[0-9]{3,6}$' , var).group()
                #print (time_str)
                #print (float(dot_sec_str)/1000)
                match_time = '2021-' + time_str
                ans_time_stamp = time.mktime(time.strptime(match_time, "%Y-%m-%d %H:%M:%S")) # 02-23 10:33:46.360  -> 1614047626.0
                ans_time_stamp_dot_sec = ans_time_stamp + float(dot_sec_str)/1000
                #print (ans_time_stamp_dot_sec)
                dict_main_temp.update({'ans_time_stamp_dot_sec':ans_time_stamp_dot_sec})


                # batteryLevel=43            4 3671 332 3 1
                var = re.search('([0-9]{1,3})\ ([0-9]{4,4})\ ([0-9]{3,3})\ ([0-9]{1,1})\ ([0-9]{1,1})' , line).group(1)
                #print (var)
                DeviceStatusMonitor_batteryLevel = int(re.search('[0-9]{1,3}' , var).group())
                #print (DeviceStatusMonitor_batteryLevel)
                dict_main_temp.update({'DeviceStatusMonitor_batteryLevel':DeviceStatusMonitor_batteryLevel})
                
                # batteryVoltage=4128            4 3671 332 3 1
                var = re.search('([0-9]{1,3})\ ([0-9]{4,4})\ ([0-9]{3,3})\ ([0-9]{1,1})\ ([0-9]{1,1})' , line).group(2)
                #print (var)
                DeviceStatusMonitor_batteryVoltage = int(re.search('[0-9]{1,4}' , var).group())
                #print (DeviceStatusMonitor_batteryVoltage)
                dict_main_temp.update({'DeviceStatusMonitor_batteryVoltage':DeviceStatusMonitor_batteryVoltage})

                # batteryTemperature=443            4 3671 332 3 1
                var = re.search('([0-9]{1,3})\ ([0-9]{4,4})\ ([0-9]{3,3})\ ([0-9]{1,1})\ ([0-9]{1,1})' , line).group(3)
                #print (var)
                DeviceStatusMonitor_batteryTemperature = int(re.search('[0-9]{1,3}' , var).group())
                #print (DeviceStatusMonitor_batteryTemperature)            4 3671 332 3 1
                dict_main_temp.update({'DeviceStatusMonitor_batteryTemperature':DeviceStatusMonitor_batteryTemperature})

                # batteryStatus=2            4 3671 332 3 1
                var = re.search('([0-9]{1,3})\ ([0-9]{4,4})\ ([0-9]{3,3})\ ([0-9]{1,1})\ ([0-9]{1,1})' , line).group(4)
                #print (var)
                DeviceStatusMonitor_batteryStatus = int(re.search('[0-9]{1,1}' , var).group())
                #print (DeviceStatusMonitor_batteryStatus)
                dict_main_temp.update({'DeviceStatusMonitor_batteryStatus':DeviceStatusMonitor_batteryStatus})

                # batteryHealth=2            4 3671 332 3 1
                var = re.search('([0-9]{1,3})\ ([0-9]{4,4})\ ([0-9]{3,3})\ ([0-9]{1,1})\ ([0-9]{1,1})' , line).group(5)
                #print (var)
                DeviceStatusMonitor_batteryHealth = int(re.search('[0-9]{1,1}' , var).group())
                #print (DeviceStatusMonitor_batteryHealth)
                dict_main_temp.update({'DeviceStatusMonitor_batteryHealth':DeviceStatusMonitor_batteryHealth})

                #print (dict_main_temp)

                list_main.append(dict_main_temp)
                dict_main_temp = {}

                #print (list_main)

    fin_main.close()

    #fin_kernel = open(filename_kernel, 'r')
    fin_kernel = codecs.open(filename_kernel, 'r',encoding= u'utf-8',errors='ignore')

    for line in fin_kernel.readlines():
        line = line.strip()                             #remove tab and space
        if re.match('.+healthd:\ battery', line):
            #print ("%s" % (line) )

            # 130425.299122
            # <14>[114934.753885]
            var = re.search('^.*\[.+[0-9]{1,6}\.[0-9]{1,6}.' , line).group()
            #print (var)
            healthd_time = float(re.search('[0-9]{1,6}\.[0-9]{1,6}' , var).group())
            #healthd_time = healthd_time1 * 1000000
            #print (healthd_time)
            dict_kernel_temp.update({'healthd_time':healthd_time})

            # l=37
            var = re.search('l=[0-9]{1,3}' , line).group()
            #print (var)
            healthd_capacity = int(re.search('[0-9]{1,3}' , var).group())
            #print (healthd_capacity)
            dict_kernel_temp.update({'healthd_capacity':healthd_capacity})

            # v=3769
            var = re.search('v=[0-9]{1,4}' , line).group()
            #print (var)
            healthd_voltage_now = int(re.search('[0-9]{1,4}' , var).group())
            #print (healthd_voltage_now)
            dict_kernel_temp.update({'healthd_voltage_now':healthd_voltage_now})

            # t=24.0
            var = re.search('t=[0-9]{1,3}.[0-9]{1,3}' , line).group()
            #print (var)
            healthd_temp = float(re.search('[0-9]{1,3}.[0-9]{1,3}' , var).group())
            #print (healthd_temp)
            dict_kernel_temp.update({'healthd_temp':healthd_temp})

            # h=1
            var = re.search('h=[0-9]{1,1}' , line).group()
            #print (var)
            healthd_health = int(re.search('[0-9]{1,1}' , var).group())
            #print (healthd_health)
            dict_kernel_temp.update({'healthd_health':healthd_health})

            # st=3
            var = re.search('st=[0-9]{1,1}' , line).group()
            #print (var)
            healthd_status = int(re.search('[0-9]{1,1}' , var).group())
            #print (healthd_status)
            dict_kernel_temp.update({'healthd_status':healthd_status})

            list_kernel.append(dict_kernel_temp)
            dict_kernel_temp = {}
            #print (list_kernel)
            
    fin_kernel.close()

    #for dict_main_temp in list_main:
    #    print (dict_main_temp)
    #for dict_kernel_temp in list_kernel:
    #    print (dict_kernel_temp)


    if module_DeviceStatusMonitor :
        for dict_main_temp in list_main:
            #print (dict_main_temp)
            ans_time_stamp_dot_sec = dict_main_temp['ans_time_stamp_dot_sec']
            DeviceStatusMonitor_batteryLevel = dict_main_temp['DeviceStatusMonitor_batteryLevel']
            DeviceStatusMonitor_batteryVoltage = dict_main_temp['DeviceStatusMonitor_batteryVoltage']
            DeviceStatusMonitor_batteryTemperature = dict_main_temp['DeviceStatusMonitor_batteryTemperature']
            DeviceStatusMonitor_batteryStatus = dict_main_temp['DeviceStatusMonitor_batteryStatus']
            DeviceStatusMonitor_batteryHealth = dict_main_temp['DeviceStatusMonitor_batteryHealth']
            #print (str(ans_time_stamp_dot_sec) + " " + str(DeviceStatusMonitor_batteryLevel) + " " + str(DeviceStatusMonitor_batteryVoltage) + " " + str(DeviceStatusMonitor_batteryTemperature) + " " + str(DeviceStatusMonitor_batteryHealth) + " " + str(DeviceStatusMonitor_batteryStatus))

            #for key,value in dict_main_temp.items():
            #    print(key,value)

            for dict_kernel_temp in list_kernel:
                #print (dict_kernel_temp)
                healthd_time = dict_kernel_temp['healthd_time']
                healthd_capacity = dict_kernel_temp['healthd_capacity']
                healthd_voltage_now = dict_kernel_temp['healthd_voltage_now']
                healthd_temp = dict_kernel_temp['healthd_temp']
                healthd_health = dict_kernel_temp['healthd_health']
                healthd_status = dict_kernel_temp['healthd_status']
                #print (str(healthd_time) + " " + str(healthd_capacity) + " " + str(healthd_voltage_now) + " " + str(healthd_temp) + " " + str(healthd_health) + " " + str(healthd_status))
                #for key,value in dict_kernel_temp.items():
                #    print(key,value)
                if DeviceStatusMonitor_batteryLevel == healthd_capacity :
                    if DeviceStatusMonitor_batteryVoltage == healthd_voltage_now :
                        if DeviceStatusMonitor_batteryTemperature == healthd_temp * 10 :
                            #print (str(ans_time_stamp_dot_sec) + " " + str(DeviceStatusMonitor_batteryLevel) + " " + str(DeviceStatusMonitor_batteryVoltage) + " " + str(DeviceStatusMonitor_batteryTemperature) + " " + str(DeviceStatusMonitor_batteryHealth) + " " + str(DeviceStatusMonitor_batteryStatus))
                            #print (str(healthd_time) + " " + str(healthd_capacity) +" " + str(healthd_voltage_now) + " " + str(healthd_temp) + " " + str(healthd_health) + " " + str(healthd_status))
                            #print (int(ans_time_stamp_dot_sec - healthd_time))
                            list_result.append(int(ans_time_stamp_dot_sec - healthd_time))

    if module_BatteryBroadcastReceiver :
        for dict_main_temp in list_main:
            #print (dict_main_temp)
            ans_time_stamp_dot_sec = dict_main_temp['ans_time_stamp_dot_sec']
            bbr_batteryLevel = dict_main_temp['bbr_batteryLevel']
            bbr_batteryVoltage = dict_main_temp['bbr_batteryVoltage']
            bbr_batteryTemperature = dict_main_temp['bbr_batteryTemperature']
            bbr_batteryStatus = dict_main_temp['bbr_batteryStatus']
            bbr_batteryHealth = dict_main_temp['bbr_batteryHealth']
            #print (str(ans_time_stamp_dot_sec) + " " + str(bbr_batteryLevel) + " " + str(bbr_batteryVoltage) + " " + str(bbr_batteryTemperature) + " " + str(bbr_batteryHealth) + " " + str(bbr_batteryStatus))

            #for key,value in dict_main_temp.items():
            #    print(key,value)

            for dict_kernel_temp in list_kernel:
                #print (dict_kernel_temp)
                healthd_time = dict_kernel_temp['healthd_time']
                healthd_capacity = dict_kernel_temp['healthd_capacity']
                healthd_voltage_now = dict_kernel_temp['healthd_voltage_now']
                healthd_temp = dict_kernel_temp['healthd_temp']
                healthd_health = dict_kernel_temp['healthd_health']
                healthd_status = dict_kernel_temp['healthd_status']
                #print (str(healthd_time) + " " + str(healthd_capacity) + " " + str(healthd_voltage_now) + " " + str(healthd_temp) + " " + str(healthd_health) + " " + str(healthd_status))
                #for key,value in dict_kernel_temp.items():
                #    print(key,value)
                if bbr_batteryLevel == healthd_capacity :
                    if bbr_batteryVoltage == healthd_voltage_now :
                        if bbr_batteryTemperature == healthd_temp * 10 :
                            #print (str(ans_time_stamp_dot_sec) + " " + str(bbr_batteryLevel) + " " + str(bbr_batteryVoltage) + " " + str(bbr_batteryTemperature) + " " + str(bbr_batteryHealth) + " " + str(bbr_batteryStatus))
                            #print (str(healthd_time) + " " + str(healthd_capacity) +" " + str(healthd_voltage_now) + " " + str(healthd_temp) + " " + str(healthd_health) + " " + str(healthd_status))
                            #print (int(ans_time_stamp_dot_sec - healthd_time))
                            list_result.append(int(ans_time_stamp_dot_sec - healthd_time))
                            
                            
    # 找出 list_result 中出现最多的值
    s2 = []
    for i in range(0,len(list_result)):
        v = list_result.count(list_result[i])
        s2.append(v)

    m = max(s2)
    n = s2.index(m)

    print("{:d} {:d}".format(list_result[n],m))
    print (list_result[n])


    # 修改kernel志时间戳

    #fout_kernel = open(filename_kernel + "_1", 'w')
    fout_kernel = codecs.open(filename_kernel + "_1", 'w',encoding= u'utf-8',errors='ignore')
    #fin_kernel = open(filename_kernel, 'r')
    fin_kernel = codecs.open(filename_kernel, 'r',encoding= u'utf-8',errors='ignore')
    for line in fin_kernel.readlines():
        line = line.strip()                             #remove tab and space
        #print (line)
        if re.match('.+[0-9]{1,10}\.[0-9]{1,8}', line): #filter no time string line
            # 130425.299122
            # <14>[114934.753885]
            var = re.search('[0-9]{1,10}\.[0-9]{1,8}' , line).group()
            dot_sec_str = re.search('[0-9]{1,6}$' , var).group()
            #print (var)
            #print (dot_sec_str)
            new_time = list_result[n] + float(var) + 60 * 60 * 8
            #print (new_time)
            #print (time.gmtime(new_time))
            #print (time.strftime("%m-%d %H:%M:%S", time.gmtime(new_time)))
            new_time_str = str(time.strftime("%m-%d %H:%M:%S", time.gmtime(new_time)) + "." + dot_sec_str)
            #num = re.sub('[0-9]{1,10}\.[0-9]{1,8}', new_time_str, line)
            
            #print (new_time_str + " " + line)
            fout_kernel.write(new_time_str + " " + line + "\n")
    fin_kernel.close()
    fout_kernel.close()

    # 合并 kernel_l 和 main 在一个文件上

    fout_main = open(filename_main + "_m_k", 'w')
    #fin_kernel = open(filename_kernel + "_1", 'r')
    fin_kernel = codecs.open(filename_kernel + "_1", 'r',encoding= u'utf-8',errors='ignore')
    for line in fin_kernel.readlines():
        line = line.strip()
        if re.match('.+healthd\ *:\ battery', line):
            fout_main.write(line + "\n")
    fin_kernel.close()
    #fin_main = open(filename_main, 'r', encoding='UTF-8')  # UnicodeDecodeError: 'gbk' codec can't decode byte 0xaf in position 2900: ill
    fin_main = codecs.open(filename_main, 'r',encoding= u'utf-8',errors='ignore')

    for line in fin_main.readlines():
        line = line.strip()
        #print (line)
        if re.match('.+VM_BMS.+power_supply_update:', line):
            fout_main.write(line + "\n")
        if re.match('.+BatteryBroadcastReceiver', line):
            fout_main.write(line + "\n")
        if re.match('.+DeviceStatusMonitor', line):
            fout_main.write(line + "\n")
    fin_main.close()
    fout_main.close()


if __name__ == '__main__':

    usage="python %prog -f <main log> \n \
    python %prog -f <main log> -m all\n \
    python %prog -f <main log> -m power_supply_update+BatteryBroadcastReceiver+DeviceStatusMonitor+healthd\n \
    python %prog -f <main log> -p u3x|u3\n \
    egrep \"power_supply_update|BatteryBroadcastReceiver|DeviceStatusMonitor|health\" * -r | sed -r 's/main.+\.log://g'| sed -r 's/bootloglogcat_.+\.log://g'| sort.exe > v.log \
    python %prog -p u3x|u3 -f <main log> -k <kernel log>\n \
    "  #
    parser=optparse.OptionParser(usage)  #
    parser.add_option('-f',dest='File_main',type='string',help='main log')
    parser.add_option('-k',dest='File_kernel',type='string',help='kernel log')
    parser.add_option('-m',dest='Module',type='string',help='module log')
    parser.add_option('-p',dest='Phone',type='string',help='phone ')
    (options,args)=parser.parse_args()

    print(options.File_main, "%s" %sys._getframe().f_lineno)
    print(options.File_kernel, "%s" %sys._getframe().f_lineno)
    print(options.Module, "%s" %sys._getframe().f_lineno)
    print(options.Phone, "%s" %sys._getframe().f_lineno)

    if options.File_main and options.File_kernel and options.Phone :
        merge_main_kernel(options.File_main, options.File_kernel, options.Module, options.Phone)
        exit (0)

    if (options.File_main and (not options.File_kernel)) or ((not options.File_main) and options.File_kernel) :
        analyse(options.File_main, options.File_kernel, options.Module, options.Phone)
    else :
        print (usage)





